import { getWebsocketUrl, APPID, encodeText, splitText } from "./config";
import type { NameFace, ChatOption } from "./config";
import storage from "@/utils/storage";
import { Ref } from "vue";
interface MessageData {
  data: string;
}
interface TTSDataFace {
  code: number;
  data: {
    /**
     * 语音base64文件
     */
    audio: string;
    ced: string;
    /**
     * 会话状态，取值为[0,1,2]；0代表首次结果；1代表中间结果；2代表最后一个结果
     */
    status: number;
  };
  message: string;
  sid: string;
}

class TTS {
  TO?: string; // 用户id，不传回 每次new 自动随机生成一个
  data: string[]; // 一条消息星火模型会多次webscoket 返回，所以进行拼接
  resolve?: any; // 成功后的回调
  APPID: string;
  awaitList: string[]; // 消息队列
  callbackMessages?: Function;
  isSend: boolean;
  url?: string; // 连接地址
  socket?: WebSocket; // socket实类
  isOnline: Ref<boolean>; // 是否连接 , 这里是考虑到每次只能发送一条，一条结束前，为true则不能让人继续发消息
  constructor(option?: ChatOption) {
    this.socket = undefined;
    this.isOnline = ref(false);
    // 初始化聊天对象
    this.TO = option?.uid ?? Date.parse(new Date().toString()).toString();
    this.url = getWebsocketUrl("TTS", option?.API_KEY, option?.API_SECRET);
    this.APPID = option?.APPID ?? APPID;
    this.APPID = option?.APPID ?? APPID;
    // 合并的消息
    this.data = [];
    this.resolve = undefined;
    this.awaitList = [];
    this.callbackMessages = option?.onMessage;
    this.isSend = false;
  }

  /**
   * 连接url
   * @returns WebSocket
   */
  connectSocket() {
    return new Promise((resolve, reject) => {
      const url = this.url!;
      this.socket = new WebSocket(url);
      // 监听连接成功
      // 监听连接成功
      this.socket.onopen = () => {
        this.isOnline.value = true;
        resolve(this.socket);
      };
      // 监听接收信息
      this.socket.onmessage = (e) => this.onMessage(e);
      // 监听断开
      this.socket.onclose = (e) => this.onclose(e);
      // 监听错误
      this.socket.onerror = (err) => {
        this.isOnline.value = false;
      };
    });
  }
  /**
   * 主动关闭，暂时无用
   */
  close() {
    if (this.socket) {
      this.socket.close();
      this.socket = undefined;
      this.isOnline.value = false;
    }
  }
  /**
   * 关闭后进行回调
   * 或者也可以采用 onMessage内 obj.header.status===2 来进行回调
   */
  onclose() {
    console.log("关闭");
  }
  /**
   * 收到消息
   * @param data ChatFace
   */
  onMessage(data: MessageData) {
    const obj: TTSDataFace = JSON.parse(data.data);
    console.log(obj);

    this.data.push(obj.data.audio);
    if (obj.data.status === 2) {
      storage.set("lists", this.data);
      this.isSend = false;
      this.start();
    }
    this.callbackMessages && this.callbackMessages(obj.data.audio);
  }

  getParams(str: string) {
    return {
      common: {
        app_id: this.APPID,
      },
      business: {
        aue: "raw",
        auf: "audio/L16;rate=16000",
        vcn: "xiaoyan",
        speed: 50,
        volume: 50,
        pitch: 50,
        bgs: 1,
        tte: "UTF8",
      },
      data: {
        status: 2,
        text: encodeText(str, "UTF8"),
      },
    };
  }
  start() {
    if (this.isSend) return;
    console.log(this.awaitList);
    this.isSend = true;
    if (this.awaitList.length === 0) {
      this.resolve && this.resolve(this.data);
      this.data = [];
      this.resolve = undefined;
      this.isSend = false;
    } else {
      this.connectSocket().then((res) => {
        const str = this.awaitList.shift()!;
        const params = this.getParams(str);
        this.socket?.send(JSON.stringify(params));
      });
    }
  }
  /**
   * 发送消息
   * @param str  发送的消息文字
   * @returns
   */
  send(str: string): Promise<string[]> {
    return new Promise((resolve, reject) => {
      console.log(str);
      if (!str) {
        resolve([]);
        return;
      }
      this.resolve = resolve;
      this.awaitList = this.awaitList.concat(splitText(str, 500));
      console.log(this.awaitList);
      this.start();
    });
  }
}

export default  TTS;
